package com.dengke.springsecurity.authentication;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.dengke.springsecurity.dao.UserInfoDAO;
import com.dengke.springsecurity.model.UserInfo;
/***
 * 自定义的用户服务，用于查询用户的信息，只需要重写loadUserByUsername.
 * 采用SpringSecurity时，username应是唯一的
 * @author wude
 *
 */
@Service
public class MyDBAuthenticationService implements UserDetailsService{

//	@Autowired
	@Resource(name="Hibernate")
	private UserInfoDAO userInfoDAO;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		UserInfo userInfo=userInfoDAO.findUserInfo(username);
		System.out.println("UserInfo= " + userInfo);
		 
        if (userInfo == null) {
            throw new UsernameNotFoundException("User " + username + " was not found in the database");
        }
         
        // [USER,ADMIN,..]
        List<String> roles= userInfoDAO.getUserRoles(username);
         
        List<GrantedAuthority> grantList= new ArrayList<GrantedAuthority>();
        if(roles!= null)  {
            for(String role: roles)  {
                // ROLE_USER, ROLE_ADMIN,..
            	//根据登录的用户信息，去db查找该用户的权限信息
                GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + role);
                grantList.add(authority);
            }
        }        
         
        UserDetails userDetails = (UserDetails) new User(userInfo.getUserName(), //
                userInfo.getPassword(),grantList);
 
        return userDetails;
	}

}
